from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from apps.backend import models

class PageNumberPagination(PageNumberPagination):
    page_size_query_param = 'size'
    page_size = 15
    max_page_size = 50
    def get_paginated_response(self, data):
        return {'total': self.page.paginator.count, 'list': data}
    
class MenuSerializer(serializers.ModelSerializer):
    class Meta: 
        model = models.Menus
        fields = ["id", "menu_name"]
        extra_kwargs = {
            "id": {"read_only": False},  # 数据验证
            "menu_name": {"read_only": True}  # 序列化
        }

class RoleAllSerializer(serializers.ModelSerializer):
    class Meta: 
        model = models.Roles
        fields = ["id", "role_name"]
        extra_kwargs = {
            "id": {"read_only": True},  # 数据验证
            "role_name": {"read_only": True}  # 序列化
        }     
    
class RoleModelSerializer(serializers.ModelSerializer):
    menus = MenuSerializer(many=True)
    rules = serializers.SerializerMethodField()
    rules_name = serializers.SerializerMethodField()
    statu = serializers.SerializerMethodField()
    class Meta:
        model = models.Roles
        fields = ["id", "role_name", "is_active", "rules", "menus", "rules_name", "statu"]
        extra_kwargs = {
            "rules": {"read_only": True},
            "rules_name": {"read_only": True} 
        }

    def get_rules(self, obj): 
        result = obj.menus.all()    
        idArr = []   
        for rule in result:
            idArr.append(rule.id)
        
        return idArr

    def get_rules_name(self, obj): 
        result = obj.menus.all()  
        nameStr = ''   
        for rule in result:
            nameStr = nameStr +'、'+ rule.menu_name if len(nameStr) > 0 else nameStr + rule.menu_name  
        
        return nameStr

    def get_statu(self, obj):
        if obj.is_active:
            return "启用"
        else:
            return "禁用"  

    def create(self, validated_data):
        menus_id_list = [ele['id'] for ele in validated_data.pop('menus')]
        role = models.Roles.objects.create(**validated_data)
        role.menus.add(*menus_id_list)
        return role  
        # "menus":[{"id":1}, {"id":2}],

    def update(self, instance, validated_data):
        instance.role_name = validated_data.get('role_name', instance.role_name)
        instance.is_active = validated_data.get('is_active', instance.is_active)
        instance.save()

        menus_id_list = [ele['id'] for ele in validated_data.pop('menus')]
        instance.menus.set(menus_id_list)
        return instance